<template>
  <div class="table-box">
    <ProTable
      :request-api="GetRoleList"
      :data-callback="dataCallback"
      :pagination="false"
      :tree-props="{ children: 'roles', hasChildren: 'hasChildren' }"
      :columns="columns"
      title="角色树"
      ref="ProRef"
      row-key="id"
      :expand-row-keys="['1']"
    >
      <template #tableHeader>
        <el-button type="primary" @click="addRootRole" v-auth="'添加角色'">新增角色</el-button>
      </template>
      <template #create_time="{ row }">
        {{ dayjs(row.create_time).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link :icon="Tools" v-if="row.id !== nowRootRoleId" v-auth="'设置权限'" @click="changePower(row)"
          >设置权限</el-button
        >
        <el-button type="primary" link :icon="Plus" @click="addChildRole(row)" v-auth="'添加角色'">新增子角色</el-button>
        <el-button type="primary" link :icon="EditPen" @click="editRole(row)" v-auth="'编辑角色'">编辑</el-button>
        <el-button type="primary" link :icon="Delete">删除</el-button>
      </template>
    </ProTable>
    <role-drawer ref="RoleDrawerRef"></role-drawer>
    <power-role ref="PowerRef"></power-role>
  </div>
</template>

<script setup lang="ts" name="roleManage">
import ProTable from "@/components/ProTable/index.vue";
import { GetRoleList, AddRole, EditRole } from "@/api/modules/role";
import { ColumnProps } from "@/components/ProTable/interface";
import { Plus, EditPen, Delete, Tools } from "@element-plus/icons-vue";
import RoleDrawer from "./components/RoleDrawer.vue";
import PowerRole from "./components/PowerRole.vue";
import { ref } from "vue";
import dayjs from "dayjs";
import { getFlatRoleList } from "@/utils";
import { Role } from "@/api/interface/role";

import { useAuthStore } from "@/stores/modules/auth";
const { flatMenuListGet } = useAuthStore();

const ProRef = ref<InstanceType<typeof ProTable> | null>();
const PowerRef = ref<InstanceType<typeof PowerRole> | null>();

const columns: ColumnProps[] = [
  { type: "index", label: "#", width: 50 },
  { prop: "roleName", label: "角色名称" },
  { prop: "create_time", label: "创建时间" },
  { prop: "operation", label: "操作", width: 350 }
];

// ----------处理数据-------------
const flatRoles = ref<Role.Option[]>([]);

// 当前的顶端角色
const nowRootRoleId = ref(1);

const dataCallback = (data: any) => {
  nowRootRoleId.value = data[0].id;
  flatRoles.value = getFlatRoleList(data);
  return data;
};

// ---------抽屉相关——--------
const RoleDrawerRef = ref<InstanceType<typeof RoleDrawer> | null>(null);
const addRootRole = () => {
  const params: any = {
    rowData: undefined,
    api: AddRole,
    getTable: ProRef.value?.getTableList
  };
  RoleDrawerRef.value?.acceptParams(params);
};
const addChildRole = (row: any) => {
  const params: any = {
    rowData: {
      pid: row.id,
      roleName: "",
      roleValue: "",
      remark: "",
      sort: 100
    },
    api: AddRole,
    getTable: ProRef.value?.getTableList
  };
  RoleDrawerRef.value?.acceptParams(params);
};
const editRole = (row: any) => {
  const params = {
    rowData: row,
    api: EditRole,
    getTable: ProRef.value?.getTableList,
    isDisableSetRegion: true
  };
  RoleDrawerRef.value?.acceptParams(params);
};

// -----------设置权限

// 生成多叉树
const ManyChaTree = (list: any[], count: number = 0) => {
  let newList: any[] = [];
  for (let i = 0; i < list.length; i++) {
    newList.push({ name: list[i].meta.title, count, id: list[i].id, pid: list[i].pid, children: [], type: "route" });
    count++;
    if (list[i].apis.length !== 0) {
      for (let j = 0; j < list[i].apis.length; j++) {
        newList[i].children.push({ name: list[i].apis[j].api_name, count, id: list[i].apis[j].id, pid: list[i].id, type: "api" });
        count++;
      }
    }
  }

  return newList;
};

function buildTree(nodes: any[], pid: number): any[] {
  const tree: any[] = [];

  for (const node of nodes) {
    if (node.pid === pid) {
      if (node.type === "route") {
        const children = buildTree(nodes, node.id);
        if (children.length > 0) {
          node.children = children;
        }
      }
      tree.push(node);
    }
  }

  return tree;
}

// 构建用户的权限
const buildUserRoleTree = (route: any[], api: any[], allTree: any[]) => {
  let newTree = [];
  for (let i = 0; i < route.length; i++) {
    const index = allTree.findIndex((e: any) => e.type === "route" && e.id === route[i].id);
    if (index !== -1) {
      newTree.push(allTree[index]);
    }
  }
  let apiList = [];
  for (let i = 0; i < allTree.length; i++) {
    if (allTree[i].children.length !== 0) {
      for (let j = 0; j < allTree[i].children.length; j++) {
        if (allTree[i].children[j].type === "api") {
          apiList.push(allTree[i].children[j]);
        }
      }
    }
  }
  for (let i = 0; i < api.length; i++) {
    const index = apiList.findIndex((e: any) => e.id === api[i].id);
    if (index !== -1) {
      newTree.push(apiList[index]);
    }
  }
  return newTree;
};

// 获取路由以及资源
const getAllFlat = (data: any[]) => {
  let newList = [];
  for (let i = 0; i < data.length; i++) {
    newList.push(data[i]);
    if (data[i].children.length !== 0) {
      for (let j = 0; j < data[i].children.length; j++) {
        if (data[i].children[j].type === "api") {
          newList.push(data[i].children[j]);
        }
      }
    }
  }
  return newList;
};

const changePower = (row: any) => {
  const data = ManyChaTree(JSON.parse(JSON.stringify(flatMenuListGet)));
  const nowParams: any = {
    data: buildTree(data, 1),
    select: buildUserRoleTree(row.routes, row.apis, data),
    row,
    flat: getAllFlat(data),
    getTable: ProRef.value?.getTableList
  };
  PowerRef.value?.open(nowParams);
  return;
  const list = ManyChaTree(JSON.parse(JSON.stringify(flatMenuListGet)));
  const newList = buildTree(list, 1);
  const params: any = {
    row,
    parentList: newList,
    flatList: list,
    getTable: ProRef.value?.getTableList
  };
  console.log(params);
};
</script>
